


#include "Battary.h"
#include "LCD.h"

StructBattaryRunPara gsBattaryRunPara;


const StructBattary BattaryVoltTable[]=
{
	{4050,100},
	{3950,95},
	{3850,85},
	{3750,75},
	{3700,60},
	{3650,45},
	{3600,30},
	{3550,15},
    {3500,0}
};


void TestBattary(void)
{
	unsigned short int Vxx = 4051;
	while(Vxx > 3500)
	{
		CalculateBattaryPowerPercent(Vxx);
        Vxx--;
	}
}

void GetBattaryPower(void)
{
	BattaryPowerTurnOn();
	delay_10us(10);
	ADCSample();
	BattaryPowerTurnOff();
       CalculateBattaryPowerPercent(gsADCParameter.Volt_Channel_10*2);
       
	//LCDShowNumber(gsBattaryRunPara.QuentityPercent);
	LCDShowPercent(gsBattaryRunPara.QuentityPercent);
}
void CheckExternVolt(void)
{
	if (gsADCParameter.Volt_Channel_10*2 > 4250)
       {
       	gsBattaryRunPara.BattaryFlag = POWER_FROM_EXTERN;
       }
       else
       {
       	gsBattaryRunPara.BattaryFlag = POWER_FROM_BATTARY;
       }
       gsBattaryRunPara.BattaryFlag = POWER_FROM_BATTARY;
}

void CalculateBattaryPowerPercent(unsigned short int Vlt)
{
	unsigned char TableSize,CurPos;
	TableSize = sizeof(BattaryVoltTable)/sizeof(BattaryVoltTable[0]);
	if (Vlt >= BattaryVoltTable[0].VoltValue)
	{
		gsBattaryRunPara.QuentityPercent = 100;
	}
	else if (Vlt <= BattaryVoltTable[TableSize -1].VoltValue)
	{
		gsBattaryRunPara.QuentityPercent = 0;
	}
	else
	{
		CurPos = BinarySearch(BattaryVoltTable,Vlt,TableSize);
		gsBattaryRunPara.QuentityPercent = \
		               BattaryVoltTable[CurPos].percent - (BattaryVoltTable[CurPos].VoltValue  - Vlt)* \
	                     (BattaryVoltTable[CurPos].percent - BattaryVoltTable[CurPos + 1].percent)/ \
	                     (BattaryVoltTable[CurPos].VoltValue - BattaryVoltTable[CurPos + 1].VoltValue) ;
		
	}
}

//unsigned short int tempv;
unsigned char BinarySearch(const StructBattary *ptr,
                                               unsigned short int Value,unsigned char num)
{
	unsigned char Low,High,Middle;
	High = num;
	Low = 0;
	/*assert num must larger than 1.*/
	while(Low <= High)
	{
              Middle = (Low + High)/2;
        //      tempv = (ptr + Middle)->VoltValue;
		if (Value == ((ptr + Middle)->VoltValue))	
		{
			break;
		}
		else
		{
			if (Value < ((ptr + Middle)->VoltValue))
			{
				Low = Middle + 1;
			}
			else
			{
				High = Middle - 1;
			}
		}
	}
	return ((Low + High)/2);
}


